import { ipcMain } from 'electron'
import { getByNameWindow } from './windows'
import { BarTitle, NewProject } from './type'
import { selectDirectory } from './directory'
import * as path from 'node:path'
import * as fs from 'node:fs'
import * as git from 'isomorphic-git'
import * as http from 'isomorphic-git/http/node'
import { generateTree } from '../renderer/src/utils/file'
import { handlerTemplateFile, readFile, writeFile } from './file'

export default () => {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  ipcMain.on('controlFrame', (_, value: boolean) => {
    if (value) {
      const byNameWindow = getByNameWindow('start')
      if (byNameWindow) {
        byNameWindow.close()
      }
      getByNameWindow('createProject')
    }
  })
  ipcMain.on('openMain', () => {
    const byNameWindow = getByNameWindow('createProject')
    if (byNameWindow) {
      byNameWindow.close()
    }
    getByNameWindow('main')
  })
  ipcMain.on('setBarTitle', (_, value: BarTitle) => {
    if (value) {
      const byNameWindow = getByNameWindow(value.type)
      if (byNameWindow) {
        byNameWindow.setTitle(value.text)
      }
    }
  })

  ipcMain.on('downloadViteTemplate', async (event: Electron.IpcMainEvent, value: NewProject) => {
    const dir = path.join(value.path, value.title)
    await git.clone({ fs, http, dir, url: 'https://gitee.com/jack_whh/vitepress-doc-template.git' })
    const tree = generateTree(dir)
    await handlerTemplateFile(tree, value)
    event.sender.send('projectTree', tree)
  })

  ipcMain.on('fileValueByPath', async (event: Electron.IpcMainEvent, value: string) => {
    const data = await readFile(value)
    event.sender.send('readFile', data)
  })

  ipcMain.handle('selectDirectory', async () => {
    return selectDirectory()
  })
  ipcMain.on(
    'saveFile',
    async (_event: Electron.IpcMainEvent, value: { path: string; content: string }) => {
      const { path, content } = value
      await writeFile(path, content)
    }
  )
}
